package cn.walls1717.wallsmall.ware.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.walls1717.wallsmall.common.utils.PageUtils;
import cn.walls1717.wallsmall.common.utils.Query;
import cn.walls1717.wallsmall.common.utils.R;
import cn.walls1717.wallsmall.ware.dao.WareInfoDao;
import cn.walls1717.wallsmall.ware.entity.WareInfoEntity;
import cn.walls1717.wallsmall.ware.feign.MemberFeignService;
import cn.walls1717.wallsmall.ware.service.WareInfoService;
import cn.walls1717.wallsmall.ware.pojo.vo.FareVO;
import cn.walls1717.wallsmall.ware.pojo.vo.MemberAddressVO;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {
    @Resource
    private MemberFeignService memberFeignService;

    /**
     * 分页条件查询
     * 
     * @param params 条件参数
     * @return 分页数据
     */
    @Override
    public PageUtils listPagesByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<WareInfoEntity> lqw = new LambdaQueryWrapper<>();
        String key = (String)params.get("key");
        if (!StrUtil.isEmpty(key)) {
            lqw.eq(WareInfoEntity::getId, key).or().like(WareInfoEntity::getName, key).or()
                .like(WareInfoEntity::getAddress, key).or().like(WareInfoEntity::getAreacode, key);
        }
        IPage<WareInfoEntity> page = this.page(new Query<WareInfoEntity>().getPage(params), lqw);
        return new PageUtils(page);
    }

    /**
     * 根据addressId计算运费
     *
     * @param addrId addressId
     * @return 运费
     */
    @Override
    public FareVO getFareByAddressId(Long addrId) {
        R r = memberFeignService.getAddressById(addrId);
        FareVO fareVO = new FareVO();
        MemberAddressVO address = r.getData("memberReceiveAddress", new TypeReference<MemberAddressVO>() {});
        if (address == null) {
            return null;
        }
        String phone = address.getPhone();
        String substring = phone.substring(phone.length() - 1);
        BigDecimal fare = new BigDecimal(substring);
        fareVO.setAddress(address);
        fareVO.setFare(fare);
        return fareVO;
    }

}